<?php

class EstimateHelper extends Helper
{

    private $check_rule;
    private $_field;
    protected $loan_mode;
    protected $mode;

    public function __construct()
    {
        $this->check_rule = array(
            'et_name' => array('require', '客户姓名不能为空'),
            'et_car_type' => array('require', '车辆类型不能为空'),
            'et_car_model' => array('require', '车辆型号不能为空'),
            'et_car_date' => array('require', '上牌注册日期不能为空'),
        );
        $this->_field = array('et_id', 'et_name', 'et_code', 'et_car_type', 'et_car_model', 'et_bank','et_car_date',
            'et_remarks', 'et_br_name', 'et_sname', 'et_stime', 'et_ftime', 'et_fname', 'et_price', 'et_status',
            'et_o_number','et_attach','et_fremarks','et_price_one','et_price_two','et_remarks_two','et_stime_two','et_sid','et_car_fullmodel','et_seat_number');
        $mode = Config::GetCommon();
        $this->mode = $mode;
        $this->loan_mode = $mode['mode'];
    }

    /**
     * 单条数据
     * @param type $where
     * @return type
     */
    public function estimateRow($where)
    {
        if (is_numeric($where)) {
            $where = array('`et_id` = ?' => $where);
        }
        $estimateModel = $this->LoadModel('Public');
        $data = $estimateModel->getOneRow('estimate', $this->_field, $where);
        return $data;
    }

    /**
     * 单条数据
     * @param type $where
     * @return type
     */
    public function downRow($where)
    {
        $estimateModel = $this->LoadModel('Public');
        $data = $estimateModel->getOneRow('estimate', $this->_field, $where);
        return $data;
    }

    /**
     * 所有数据
     * @param type $where
     * @return type
     */
    public function estimateAll($bank,$id,$whe)
    {
        $model = $this->LoadModel('Public');
        if($id){
            $where['`et_br_id` = ?']=$id;
        }
        if($whe){
            $where['`et_status`= ?']=$whe;
        }
        if($bank){
            $where['`et_bank` in (?)']=array(0,$bank);
        }
        $data['all'] = $model->getList('estimate', $this->_field, $where);
        return $data;
    }

    /**
     * 分页
     * @param type $where
     * @param type $page
     * @param type $limit
     * @param type $param
     * @return type
     */
    public function estimateList($where, $page = 1, $limit = PAGE_SIZE, $param = array(),$member)
    {
        //$where['`et_status` != ?'] = '作废';
        $model = $this->LoadModel('Public');
        if (!empty($member)) {
            switch ($member['u_scope']) {
                case '用户级':
//                    if (!empty($member['u_bank'])) {
//                        $where['`o_bank_id` IN (?)'] = explode(',', $member['u_bank']);
//                    } else {
//                        $where['`o_bank_id` IN (?)'] = array(0);
//                    }
                    if ($member['u_dp_type'] == 'rg') {
                        $dot_id = array(0);
                        $branch = $model->getList('branch', array('br_id'), array('`br_uid` = ?' => $member['u_id'], '`br_status` = ?' => 'ok'));
                        if (!empty($branch)) {
                            foreach ($branch as $k => $v) {
                                $dot_id[] = $v['br_id'];
                            }
                        }
                        $where['`et_br_id` IN (?)'] = $dot_id;
                    }else{
                        $where['`et_sid` = ?'] = $member['u_id'];
                    }
                    break;
                case '部门级':
                    switch ($member['u_dp_type']) {
                        case 'dp': //部门
                            $where['`et_br_id` = ?'] = $member['u_dp_id'];
                            break;
                        case 'dot'://网点 自己网点的订单
                            $where['`et_br_id` = ?'] = $member['u_dp_id'];
                            break;
                        case 'rg'://大区 大区下所有网点订单
                            $dot_id = array(0);
                            $branch = $model->getList('branch', array('br_id'), array('`br_rgid` = ?' => $member['u_dp_id'], '`br_status` = ?' => 'ok'));
                            if (!empty($branch))
                                foreach ($branch as $k => $v) {
                                    $dot_id[] = $v['br_id'];
                                }
                            $where['(`et_br_id` = ' . $member['u_dp_id'] . ')'] = $dot_id;
                            break;
                    }
                    if (in_array($member['u_dp_type'], array('dp'))) {
                        if (!empty($member['u_bank'])) {
                            $et_bank=explode(',', $member['u_bank']);
                            if(in_array(13,$et_bank)){
                                $n=count($et_bank);
                                $et_bank[$n]=0;
                            }
                            $where['`et_bank` IN (?)'] = $et_bank;
                        } else {
                            $where['`et_bank` IN (?)'] = array(0);
                        }
                    }
                    break;
                case '单位级':
                    if (!empty($member['u_bank'])) {
                        $et_bank=explode(',', $member['u_bank']);
                        if(in_array(13,$et_bank)){
                            $n=count($et_bank);
                            $et_bank[$n]=0;
                        }
                        $where['`et_bank` IN (?)'] = $et_bank;
                    }
                    break;
                default :
                    $where['`et_sid` = ?'] = $member['u_id'];
            }
        }
        $where = array_merge($where, $this->etCondition($param));
        $data['count'] = $model->getRowCount('estimate', $where);
        if (!empty($data['count'])) {
            $data['all'] = $model->getList('estimate', $this->_field, $where, array($page, $limit), null, array("FIELD(`et_status`, '待评估','已评估','退回','已使用','作废')", "`et_ftime` DESC"));
            Pagination::SetUrl($Param);
            $data['page'] = Pagination::GetHtml($limit, $page, $data['count']);
        }
        return $data;
    }


    /**
     * 查询条件合成
     * @param type $param
     * @return type
     */
    public function etCondition($param)
    {
        $where = array();
        if (!empty($param['et_name'])) {
            $where['`et_name` LIKE ?'] = '%'.$param['et_name'].'%';
        }
        return $where;
    }

    /**
     *
     * 作废
     *
     */
    public function estimateRemove($where)
    {
        if (is_numeric($where)) {
            $where = array('`et_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $result = $model->update('estimate', array('et_status' => '作废'), $where);
        return $result;
    }


    public function estimateRet($params,$where)
    {
        if (is_numeric($where)) {
            $where = array('`et_id` = ?' => $where);
        }
        $params['et_status']='退回';

        $model = $this->LoadModel('Public');
        $result = $model->update('estimate',$params, $where);
        if($result==1){
            return array('success' => true, 'msg' => '退单成功');
        }else{
            return array('success' => false, 'msg' => '出现异常');
        }
    }

    /**
     * 数据保存
     * @param type $data
     * @param type $where
     * @return type
     */
    public function estimateSave($data, $where = '')
    {
        if (is_numeric($where)) {
            $et_id = $where;
            $where = array('`et_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        if($data['et_car'] || $data['et_plate'] || $data['et_comp']){
        $data['et_attach']=array(
            'car'=>$data['et_car'],
            'plate'=>$data['et_plate'],
            'comp'=>$data['et_comp'],
        );
          $data['et_attach']=serialize($data['et_attach']);}
        if (empty($where)) {
            $validator = Validator::checkRule($data, $this->check_rule);
            if (!$validator['pass']) {
                return array('success' => false, 'msg' => $validator['msg']);
            }
            $result = $model->save('estimate', $data);
            if ($result) {
                return array('success' => true, 'msg' => $result);

            } else {
                return array('success' => false, 'msg' => '保存失败');
            }
        } else {
            $model->update('estimate', $data, $where);
            return array('success' => true,'msg' => $et_id);
        }
    }


    public function attachmentOut($data)
    {
        $mode_arr = array('car', 'plate', 'comp');
        $data=unserialize($data);
        //file_put_contents('D:\work\chedai\www\wwwroot\dd13.txt',var_export($data['et_car'],true));
        $return_data = array();
        foreach ($mode_arr as $k => $v) {
            $return_data[$v] = empty($data[$v]) ? array() : $data[$v];
            $return_data[$v . '_url'] = empty($data[$v]) ? array() : StringCode::doUrlimage($return_data[$v]);
            if (!empty($return_data[$v])) {
                foreach ($return_data[$v] as $tkey => $tval) {
                    $file_name = end(explode('/', $tval));
                    $thumb_image = str_replace($file_name, 's_' . $file_name, $tval);
                    $return_data[$v . '_thurl'][$tkey] = is_file(WEB_PATH . $thumb_image) ? StringCode::doUrlimage($thumb_image) : StringCode::doUrlimage($tval);
                }
            }
        }
        return $return_data;
    }
    public function attachUrl($data)
    {
        $data=unserialize($data);
        $img = array();
        foreach ($data as $k => $v) {
            foreach ($v as $key => $value) {
                $img[] = $value;
            }
        }
        return $img;
    }

    public function updateAttachtemp($et_id,$temp_id){
        if(empty($et_id)) return false;
        $model = $this->LoadModel('Public');
        try{
            $model->update('attachment',array('temp_id' => $et_id),array('`temp_id` =?' => $temp_id,'`delete_status` =?' => 0));
        } catch (Exception $ex){
            return false;
        }
        return true;
    }

}
